package com.tao.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tao.config.MyLog;
import com.tao.pojo.Role;
import com.tao.pojo.vo.ResponseResult;
import com.tao.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/role")
public class CmsRoleController {
    @Autowired
    private RoleService roleService;

    @MyLog("角色列表")
    @PreAuthorize("hasAnyAuthority('admin')")
    @PostMapping("/list")
    public Object list(@RequestBody Role role){
        LambdaQueryWrapper<Role> lqw = new LambdaQueryWrapper<>();
        lqw.like(!ObjectUtils.isEmpty(role.getName()),Role::getName,role.getName());
        List<Role> list = roleService.list(lqw);
        return ResponseResult.success(list);
    }

    @MyLog("角色新增")
    @PreAuthorize("hasAnyAuthority('admin')")
    @PostMapping("/add")
    public Object add(@RequestBody Role role){
       roleService.save(role);
        return ResponseResult.success(null);
    }

    @MyLog("角色修改")
    @PreAuthorize("hasAnyAuthority('admin')")
    @PostMapping("/update")
    public Object update(@RequestBody Role role){
        roleService.updateById(role);
        return ResponseResult.success(null);
    }

    @MyLog("角色删除")
    @PreAuthorize("hasAnyAuthority('admin')")
    @PostMapping("/remove")
    public Object remove(@RequestBody Role role){
        LambdaQueryWrapper<Role> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Role::getId,role.getId());
        List<Role> list = roleService.list(lqw);
        if (list.size()<1){
            return ResponseResult.error("角色不存在！");
        }
        roleService.removeById(role.getId());
        return ResponseResult.success(null);
    }
}
